import 'dart:async';
import 'dart:io';

import 'package:creatures_world/net/cache_manager.dart';
import 'package:creatures_world/net/mm_cache_manager.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_custom_dialog/flutter_custom_dialog.dart';
import 'package:get/get.dart' as G;
import 'package:get/get_core/src/get_main.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import '../framework/utils/dialog_utils.dart';
import 'cache_response.dart';
import 'taxon_service.dart';

class NetRequester {


  static String baseUrl = "";

  // static String baseUrl =productUrl;
  static const TIME_OUT = Duration(seconds: 60 * 2);
  static const TRANS_TIME_OUT = Duration(seconds: 60 * 1 * 30);
  static DateTime? lastLogOutTime; //上次退出时间
  static int LOGOUT_DELAY = 1000; //跳转间隔，不能频繁跳转

  late Dio dio;
  var options = BaseOptions();

  NetRequester() {
    configureDio();
  }

  void configureDio() {
    // Set default configs
    options.baseUrl = baseUrl;
    options.connectTimeout = TIME_OUT;
    options.receiveTimeout = TIME_OUT;
    options.sendTimeout = TIME_OUT;
    options.contentType = Headers.jsonContentType;
    options.responseType = ResponseType.plain;
    dio = Dio(options);
    // dio.interceptors.add(PrettyDioLogger());
    //interceptors可能会因为数据量太多，可能会导致突然崩溃(requestBody=false 能减少崩溃的可能性)
    if (TaxonService.isDebug()) {
      dio.interceptors.add(
        PrettyDioLogger(requestHeader: true, requestBody: false, responseBody: true, responseHeader: false, error: true, compact: true, maxWidth: 90),
      );
    }
  }

  Future<void> downloadFile(String url, String tempDirSubDir) async {
    //https://zhuanlan.zhihu.com/p/90071559 :IO 操作教程
    Directory guildDir = Directory('${tempDirSubDir}');
    if (!guildDir.existsSync()) {
      guildDir.createSync();
      debugPrint('文档初始化成功，文件保存路径为 ${guildDir.path}');
    }
    var fileName = url.substring(url.lastIndexOf("/") + 1);
    debugPrint("下载文件=====> " + fileName);
    await dio.download(
      url,
      "${guildDir.path}/$fileName",
      deleteOnError: true,
      onReceiveProgress: (int count, int total) {
        if (count == total) {
          debugPrint("${url}下载成功----");
        }
      },
    );
  }

  Future<Response> downloadFileWithCallBack(String url, String saveAbsPath, {ProgressCallback? progressCallback}) async {
    //https://zhuanlan.zhihu.com/p/90071559 :IO 操作教程
    return dio.download(url, saveAbsPath, deleteOnError: true, onReceiveProgress: progressCallback);
  }

  String buildQueryString(Map<String, dynamic> data) {
    return Uri(queryParameters: data.map((k, v) => MapEntry(k, v.toString()))).query;
  }

  Future<Response> get(String path, Map<String, dynamic> data, Map<String, dynamic> headers, {bool useCache=true,bool showDialog = true, CancelToken? cancelToken}) async {
    // final uniqUrl = Uri.parse(baseUrl).replace(queryParameters: data).toString();
    final uniqUrl = path + buildQueryString(data);
    if(useCache){
      debugPrint("cache url==>>  ${uniqUrl}");
      var res= await CacheManager.getCache(uniqUrl);
      if(null!=res){
        return Future.value(res);
      }
    }

    Options options = Options();
    final response = await dio.get(path, queryParameters: data, options: options, cancelToken: cancelToken);
    if(useCache){
      CacheManager.putCache(uniqUrl, response);
    }
    return response;
  }

  Future<Response> post(
    String path,
    String json,
    ResponseType responseType, {
    Map<String, dynamic> headers = const {},
    bool showDialog = true,
    ProgressCallback? proggress,
    CancelToken? cancelToken,
  }) async {
    // var ctx=Get.context;

    YYDialog? yyDialog = null;
    if (showDialog) {
      yyDialog = DialogUtils.showLoadingDialog(Get.context!, "loading...");
      // QuickAlert.show(
      //   context: Get.context!,
      //   type: QuickAlertType.loading,
      //   title: 'Loading',
      //   // customAsset: "images/loading_gif.gif",
      //   text: 'Loading data...',
      // );
    }

    try {
      //可能抛出异常的代码
      Options postOption = Options(
        method: 'POST',
        sendTimeout: TIME_OUT,
        receiveTimeout: TIME_OUT,
        contentType: Headers.jsonContentType,
        responseType: responseType,
        headers: headers,
      );
      final response = await dio.post(path, data: json, options: postOption, onSendProgress: proggress, cancelToken: cancelToken);
      return response;
    } catch (e) {
      //处理特定类型的异常
      debugPrint("exception---->" + e.toString());
      int customErrorCode = 1000;
      String errorMsg = "custom_net_error".tr;
      if (e.runtimeType == DioException) {
        errorMsg = "custom_net_error".tr;
      } else {
        errorMsg = "net_error".tr;
      }
      return Response(data: "{\"msg\":\"${errorMsg}\",\"code\":${customErrorCode}}", requestOptions: RequestOptions(), statusCode: customErrorCode);
    } finally {
      if (showDialog) {
        // Navigator.pop(Get.context!);
        try {
          if (Navigator.of(Get.context!).canPop()) {
            yyDialog?.dismiss();
          }
        } catch (e) {
          debugPrint("隐藏对话框失败..=> ${e}");
        }
      }
    }
    //一定会执行的代码
    // dio.request(path,data: data,options:options );
  }

  getRequest(String absUrl, Map<String, dynamic> param) async {
    Response response = await dio.get(absUrl, queryParameters: param, onReceiveProgress: (int count, int total) {});
    return response;
  }
}
